package com.shenyue.nbtownlet.util;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import java.io.File;

public class FileOpenUtil {

    /**
     * 使用系统API，根据url获得对应的MIME类型
     */
    public static String getMimeTypeFromUrl(String url) {
        String type = null;
        //使用系统API，获取URL路径中文件的后缀名（扩展名）
        String extension = MimeTypeMap.getFileExtensionFromUrl(url);
        if (extension != null) {
            //使用系统API，获取MimeTypeMap的单例实例，然后调用其内部方法获取文件后缀名（扩展名）所对应的MIME类型
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        Log.i("bqt", "系统定义的MIME类型为：" + type);
        return type;
    }

    /**
     * 使用系统API打开文件
     */
    public static void openFileByUri(Activity mActivity, String uri) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String mimetype = getMimeTypeFromUrl(uri);
        if (StringUtil.isNull(mimetype)) {
            // if there is no extension or there is no definite mimetype, still try to open the file
            intent.setDataAndType(Uri.parse(uri), "text/*");
        } else {
            intent.setDataAndType(Uri.parse(uri), mimetype);
        }
        // custom message for the intent
        try {
            mActivity.startActivity(Intent.createChooser(intent, "选择一个应用程序:"));
        } catch (Exception e) {
            Toast.makeText(mActivity, "系统中尚未安装处理这种类型的应用.", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 打开文件
     *
     * @param file
     */
    public static void openFile(Activity mActivity, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String mimetype = getMimeTypeFromUrl(Uri.fromFile(file).toString());
        if (StringUtil.isNull(mimetype)) {
            // if there is no extension or there is no definite mimetype, still try to open the file
            intent.setDataAndType(Uri.fromFile(file), "text/*");
        } else {
            intent.setDataAndType(Uri.fromFile(file), mimetype);
        }
        // custom message for the intent
        try {
            mActivity.startActivity(Intent.createChooser(intent, "选择一个应用程序:"));
        } catch (Exception e) {
            Toast.makeText(mActivity, "系统中尚未安装处理这种类型的应用.", Toast.LENGTH_LONG).show();
        }
    }
}